import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../public.dart';

/// 我的页面
class MyIndexPage extends StatefulWidget {
  MyIndexPage({Key key}) : super(key: key);

  @override
  _MyIndexPageState createState() {
    return _MyIndexPageState();
  }
}

class _MyIndexPageState extends State<MyIndexPage> with RouteAware {
  RefreshController _refreshController = RefreshController();
  UserProvider user;
  UserRecordProvider userRecord;
  UserAccountProvider userAccount;
  ThemeProvider theme;
  PrizeNoticeModel prizeNotice;
  String inviteCode = '-';
  Size size;
  SwiperController swiperControler;
  LoginPage loginPage;

  @override
  void initState() {
    super.initState();
    swiperControler = SwiperController();
    size = MediaQuery.of(ACGN.navGK.currentContext).size;
    providerHanddle();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    ACGN.routeObserver.subscribe(this, ModalRoute.of(context));
  }

  // @override
  // void deactivate() {
  //   super.deactivate();
  //   var bool = ModalRoute.of(context).isCurrent;
  //   if (bool) {

  //   }
  // }

  didPopNext() {
    print('didPopNext==>router');
    swiperControler.startAutoplay();
  }

  didPushNext() {
    print('didPushNext==>router');
    swiperControler.stopAutoplay();
  }

  void _onRefresh() async {
    await userRecord.setUserRecord();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000));
    _refreshController.loadComplete();
  }

  void providerHanddle() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      userAccount.setUserAccount();
      userRecord.setUserRecord();
      requestHanddle();
    });
  }

  Future requestHanddle() async {
    dynamic res = await Future.wait(
        [UserService.getPrizeNotice(), UserService.getInviteInfo()]);
    setState(() {
      prizeNotice = res[0];
      inviteCode = res[1].code;
    });
  }

  void copyInvite(code) {
    Clipboard.setData(ClipboardData(text: inviteCode));
    ACGN.toast.message('复制成功', backgroundColor: ColorUtil.rgba(0, 0, 0, 0.75));
  }

  Widget userRecordWidget(List data, String type) {
    double averageW = (size.width - 32 - 24) / 2 / 3;
    double twoW = averageW;
    double threeW = averageW - 2;
    double oneW = averageW + 10;
    double oneH = oneW / 0.75;
    int len = data.length;
    bool boolType = type == 'userread';
    dynamic initDefaultItem = boolType
        ? UserReadItemModel.fromJson({})
        : UserCollectItemModel.fromJson({});
    dynamic oneData = len > 0 ? data[0] : initDefaultItem;
    dynamic twoData = len > 1 ? data[1] : initDefaultItem;
    dynamic threeData = len > 2 ? data[2] : initDefaultItem;
    return Expanded(
        child: Column(children: [
      Container(
          width: double.infinity,
          height: oneH,
          child: Stack(children: [
            Positioned(
                right: 0,
                bottom: 0,
                width: threeW,
                child: radiusImage(threeData?.cover3x4,
                    color: theme.primaryColor)),
            Positioned(
                bottom: 0,
                right: twoW - 6,
                width: twoW,
                child:
                    radiusImage(twoData?.cover3x4, color: theme.primaryColor)),
            Positioned(
                width: oneW,
                child: radiusImage(oneData?.cover3x4,
                    color: theme.primaryColor, first: true)),
          ])),
      MenuComponent(
        title: boolType ? '历史' : '追更',
        height: 32,
        decoration: BoxDecoration(
          color: ColorUtil.rgba(40, 40, 56, 1),
          borderRadius: BorderRadius.all(Radius.circular(8)),
        ),
        margin: EdgeInsets.only(top: 8),
        padding: EdgeInsets.only(top: 4, bottom: 5, left: 8, right: 8),
        titleStyle:
            TextStyle(fontSize: 14, color: ColorUtil.rgba(255, 255, 255, 0.6)),
        onTap: () {
          Routers.navigateTo(
              boolType ? RouterPage.HISTORY_PAGE : RouterPage.PURSUE_PAGE);
        },
        hasIconArrow: false,
        rightWidgets: [
          Text(
            '$len',
            style: TextStyle(
                fontSize: 12, color: ColorUtil.rgba(255, 255, 255, 0.6)),
          ),
          SVG.icon('arrow_right',
              size: 12, color: ColorUtil.rgba(255, 255, 255, 0.6))
        ],
      )
    ]));
  }

  @override
  Widget build(BuildContext context) {
    // 使用Provider
    user = Provider.of<UserProvider>(context);
    userAccount = Provider.of<UserAccountProvider>(context);
    userRecord = Provider.of<UserRecordProvider>(context);
    theme = Provider.of<ThemeProvider>(context);
    UserAccountModel userAccountData = userAccount.data;
    loginPage = LoginPage(context, size: MediaQuery.of(context).size);
    return Scaffold(
        backgroundColor: theme.primaryColor,
        appBar: AppBar(
          title: Text('我的'),
          centerTitle: true,
          leadingWidth: 44,
          leading: BackComponent(),
          actions: <Widget>[
            GestureDetector(
              onTap: () {
                Routers.navigateTo(RouterPage.MY_EDIT);
              },
              child: Center(
                  child: SVG.icon('edit', size: 24, color: Colors.white)),
            ),
            SizedBox(
              width: 16,
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Routers.navigateTo(RouterPage.SETTING);
              },
              child: Container(
                  child: SVG.icon('set', size: 24, color: Colors.white)),
            ),
            SizedBox(
              width: 16,
            ),
          ],
        ),
        body: RefreshConfig(
            child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: false,
                controller: _refreshController,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child: SingleChildScrollView(
                    child: Column(children: [
                  Padding(
                    padding: EdgeInsets.only(
                        left: 16, top: 8, right: 16, bottom: 24),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(children: [
                          Container(
                            margin: EdgeInsets.only(right: 16),
                            child: GestureDetector(
                                onTap: () {
                                  Routers.navigateTo(RouterPage.MY_EDIT);
                                },
                                child: ClipRRect(
                                    borderRadius: BorderRadius.circular(32),
                                    child: ImagesNetworkComponent(
                                        user.data?.uhead,
                                        placeholder:
                                            'assets/images/mrtx_qumh88.png',
                                        width: 64,
                                        height: 64))),
                          ),
                          Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(user.data?.uname ?? '',
                                    style: TextStyle(
                                        height: 2,
                                        color: ColorUtil.rgba(255, 255, 255, 1),
                                        fontSize: 20)),
                                Text('ID ${user.data?.uid}',
                                    style: TextStyle(
                                        color:
                                            ColorUtil.rgba(255, 255, 255, 0.5),
                                        fontSize: 10)),
                              ]),
                        ]),
                        (user.data?.type == 'device' || user.data == null)
                            ? FlatButton(
                                onPressed: () {
                                  loginPage.init();
                                },
                                child: Text('登录'),
                                color: ColorUtil.rgba(255, 215, 59, 1),
                                height: 28,
                                minWidth: 48,
                                padding: EdgeInsets.only(left: 10, right: 10),
                                shape: RoundedRectangleBorder(
                                    side: BorderSide.none,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(24))),
                              )
                            : SizedBox.shrink()
                      ],
                    ),
                  ),
                  Container(
                      height: 24,
                      margin: EdgeInsets.only(left: 16, right: 16),
                      padding: EdgeInsets.only(left: 10, right: 10),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: ColorUtil.rgba(255, 255, 255, 0.05),
                          borderRadius: BorderRadius.all(Radius.circular(8))),
                      child: prizeNotice != null && prizeNotice.list.length > 0
                          ? Swiper(
                              autoplay: true,
                              controller: swiperControler,
                              scrollDirection: Axis.vertical,
                              itemBuilder: (BuildContext context, int index) {
                                PrizeNoticeItemModel item =
                                    prizeNotice.list[index];
                                return Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SVG.icon('notice',
                                        size: 12,
                                        color:
                                            ColorUtil.rgba(255, 255, 255, 0.6)),
                                    Container(
                                        width: 16,
                                        height: 16,
                                        margin: EdgeInsets.fromLTRB(2, 0, 2, 0),
                                        clipBehavior: Clip.hardEdge,
                                        decoration: BoxDecoration(
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(8))),
                                        child: ImagesNetworkComponent(
                                          item.uheadImage,
                                          placeholder:
                                              'assets/images/mrtx_qumh88.png',
                                          width: 16,
                                          height: 16,
                                        )),
                                    Text(
                                      '${item.uname}已提现${item.cash}元',
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: ColorUtil.rgba(
                                              255, 255, 255, 0.6)),
                                    )
                                  ],
                                );
                              },
                              itemCount: prizeNotice.list.length,
                            )
                          : SizedBox.shrink()),
                  Padding(
                    padding: EdgeInsets.only(
                        left: 16, top: 16, right: 16, bottom: 24),
                    child: userAccountData != null
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                                Expanded(
                                    flex: 1,
                                    child: Column(children: [
                                      Text('${userAccountData.scoreUnit}',
                                          style: TextStyle(
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 1),
                                              height: 1.25,
                                              fontSize: 24)),
                                      Text('我的积分',
                                          style: TextStyle(
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 0.6),
                                              fontSize: 12)),
                                    ])),
                                Expanded(
                                    flex: 1,
                                    child: Column(children: [
                                      Text('${userAccountData.scoreToday}',
                                          style: TextStyle(
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 1),
                                              height: 1.25,
                                              fontSize: 24)),
                                      Text('今日积分',
                                          style: TextStyle(
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 0.6),
                                              fontSize: 12)),
                                    ])),
                                Expanded(
                                    flex: 1,
                                    child: Column(children: [
                                      Text('${userAccountData.todayRead}分钟',
                                          style: TextStyle(
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 1),
                                              height: 1.25,
                                              fontSize: 24)),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text('今日阅读',
                                              style: TextStyle(
                                                  color: ColorUtil.rgba(
                                                      255, 255, 255, 0.6),
                                                  fontSize: 12))
                                        ],
                                      )
                                    ]))
                              ])
                        : Text('....'),
                  ),
                  Container(
                    height: 8,
                    color: ColorUtil.rgba(18, 18, 26, 1),
                  ),
                  Padding(
                      padding: EdgeInsets.only(
                          left: 16, top: 16, right: 16, bottom: 22),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Expanded(
                                flex: 1,
                                child: Column(children: [
                                  userAccountData != null &&
                                          userAccountData.isNew
                                      ? Container(
                                          child: Column(
                                          children: [
                                            Container(
                                              height: 16,
                                              padding: EdgeInsets.only(
                                                  left: 8, right: 8),
                                              decoration: BoxDecoration(
                                                  color: ColorUtil.rgba(
                                                      255, 215, 59, 1),
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(8))),
                                              child: Text(
                                                '一元秒提',
                                                style: TextStyle(
                                                    fontSize: 10,
                                                    color: ColorUtil.rgba(
                                                        51, 51, 51, 1)),
                                              ),
                                            ),
                                            // 三角形
                                            RotatedBox(
                                                quarterTurns: 90,
                                                child: ClipPath(
                                                    child: Container(
                                                      height: 4,
                                                      width: 6,
                                                      color: ColorUtil.rgba(
                                                          255, 215, 59, 1),
                                                    ),
                                                    clipper: TrianglePath())),
                                          ],
                                        ))
                                      : SizedBox.shrink(),
                                  SVG.svg('jifentixian', size: 32),
                                  Text('积分提现',
                                      style: TextStyle(
                                          color: ColorUtil.rgba(
                                              255, 255, 255, 0.6),
                                          fontSize: 12)),
                                ])),
                            Expanded(
                                flex: 1,
                                child: Column(children: [
                                  Container(
                                      child: Column(
                                    children: [
                                      Container(
                                        height: 16,
                                        padding:
                                            EdgeInsets.only(left: 8, right: 8),
                                        decoration: BoxDecoration(
                                            color:
                                                ColorUtil.rgba(255, 215, 59, 1),
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(8))),
                                        child: Text(
                                          '赚30元',
                                          style: TextStyle(
                                              fontSize: 10,
                                              color: ColorUtil.rgba(
                                                  51, 51, 51, 1)),
                                        ),
                                      ),
                                      // 三角形
                                      RotatedBox(
                                          quarterTurns: 90,
                                          child: ClipPath(
                                              child: Container(
                                                height: 4,
                                                width: 5,
                                                color: ColorUtil.rgba(
                                                    255, 215, 59, 1),
                                              ),
                                              clipper: TrianglePath())),
                                    ],
                                  )),
                                  SVG.svg('yaoqinghaoyou', size: 32),
                                  Text('邀请好友',
                                      style: TextStyle(
                                          color: ColorUtil.rgba(
                                              255, 255, 255, 0.6),
                                          fontSize: 12)),
                                ])),
                            Expanded(
                                flex: 1,
                                child: GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      Routers.navigateTo(RouterPage.MY_ACCOUNT);
                                    },
                                    child: Container(
                                        alignment: Alignment.centerLeft,
                                        child: Column(children: [
                                          SVG.svg('wodezhanghu', size: 32),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              Text('我的账户',
                                                  style: TextStyle(
                                                      color: ColorUtil.rgba(
                                                          255, 255, 255, 0.6),
                                                      fontSize: 12))
                                            ],
                                          )
                                        ]))))
                          ])),
                  Container(
                    height: 1,
                    margin: EdgeInsets.only(left: 16, right: 16, bottom: 16),
                    color: ColorUtil.rgba(18, 18, 26, 1),
                  ),
                  Padding(
                      padding: EdgeInsets.only(left: 16, right: 16),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '邀请好友获得30元提现额度',
                              style: TextStyle(
                                  fontSize: 14,
                                  color: ColorUtil.rgba(255, 255, 255, 0.9)),
                            ),
                            GestureDetector(
                              onTap: () {
                                Routers.navigateTo(RouterPage.WEB,
                                    params: {'url': ACGN.config.userInviteUrl});
                              },
                              child: Row(
                                children: [
                                  Text(
                                    '查看详情',
                                    style: TextStyle(
                                        fontSize: 12,
                                        color:
                                            ColorUtil.rgba(255, 255, 255, 0.6)),
                                  ),
                                  SVG.icon('arrow_right',
                                      size: 12,
                                      color: ColorUtil.rgba(255, 255, 255, 0.6))
                                ],
                              ),
                            )
                          ])),
                  Padding(
                      padding: EdgeInsets.only(left: 16, top: 24, right: 16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                              child: Column(children: [
                            GestureDetector(
                                onTap: () {
                                  print('$inviteCode');
                                  copyInvite(inviteCode);
                                },
                                child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.only(bottom: 8),
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '$inviteCode',
                                            style: TextStyle(
                                                fontSize: 20,
                                                color: ColorUtil.rgba(
                                                    255, 255, 255, 0.9)),
                                          ),
                                          SVG.icon('copy',
                                              size: 12,
                                              color: ColorUtil.rgba(
                                                  255, 255, 255, 0.6))
                                        ]))),
                            Text('我的邀请码',
                                style: TextStyle(
                                    fontSize: 12,
                                    color: ColorUtil.rgba(255, 255, 255, 0.6)))
                          ])),
                          Container(
                            width: 180,
                            margin: EdgeInsets.only(left: 30),
                            child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  ACGN.toast.dialog(context,
                                      constraints:
                                          BoxConstraints(maxWidth: 280),
                                      content: Text(
                                        '项目开发中，敬请期待~',
                                        style: TextStyle(color: Colors.white),
                                      ));
                                },
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Column(
                                      children: [
                                        Padding(
                                            padding: EdgeInsets.only(bottom: 4),
                                            child: SVG.icon(
                                              'share_qq',
                                              size: 32,
                                              color: Colors.yellow,
                                            )),
                                        Text('QQ',
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: ColorUtil.rgba(
                                                    255, 255, 255, 0.6)))
                                      ],
                                    ),
                                    Column(
                                      children: [
                                        Padding(
                                            padding: EdgeInsets.only(bottom: 4),
                                            child: SVG.icon(
                                              'share_wx',
                                              size: 32,
                                              color: Colors.yellow,
                                            )),
                                        Text('微信',
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: ColorUtil.rgba(
                                                    255, 255, 255, 0.6)))
                                      ],
                                    ),
                                    Column(
                                      children: [
                                        Padding(
                                            padding: EdgeInsets.only(bottom: 4),
                                            child: SVG.icon(
                                              'share_qqkj',
                                              size: 32,
                                              color: Colors.yellow,
                                            )),
                                        Text('QQ空间',
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: ColorUtil.rgba(
                                                    255, 255, 255, 0.6)))
                                      ],
                                    ),
                                    Column(
                                      children: [
                                        Padding(
                                            padding: EdgeInsets.only(bottom: 4),
                                            child: SVG.icon(
                                              'share_py',
                                              size: 32,
                                              color: Colors.yellow,
                                            )),
                                        Text('朋友圈',
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: ColorUtil.rgba(
                                                    255, 255, 255, 0.6)))
                                      ],
                                    ),
                                  ],
                                )),
                          )
                        ],
                      )),
                  userRecord != null
                      ? Padding(
                          padding:
                              EdgeInsets.only(left: 16, top: 24, right: 16),
                          child: Row(children: [
                            userRecordWidget(
                                userRecord?.userCollect, 'usercollect'),
                            Container(
                              width: 24,
                            ),
                            userRecordWidget(userRecord?.userRead, 'userread')
                          ]))
                      : SizedBox.shrink(),
                  Padding(
                      padding: EdgeInsets.only(left: 16, top: 24, right: 16),
                      child: Column(children: [
                        // _menu('我的下载'),
                        MenuComponent(
                          title: '设置',
                          decoration: BoxDecoration(),
                          onTap: () {
                            Routers.navigateTo(RouterPage.SETTING);
                          },
                        ),
                        // MenuComponent(
                        //   title: '帮助反馈',
                        // ),
                        MenuComponent(
                          title: '联系我们',
                          onTap: () {
                            Routers.navigateTo(RouterPage.WEB,
                                params: {'url': ACGN.config.contactus});
                          },
                        ),
                      ]))
                ])))));
  }

  Widget radiusImage(String image, {bool first = false, Color color}) {
    Widget child;
    double outerRadius = 6;
    double innerRadius = outerRadius - 1;
    Widget _image = ImagesNetworkComponent(image);
    if (first) {
      child = Container(
          decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(outerRadius),
              border: Border.all(
                color: ColorUtil.rgba(79, 79, 102, 1), //边框颜色
                width: 1, //边框宽度
              )),
          child: ClipRRect(
              borderRadius: BorderRadius.circular(innerRadius), child: _image));
    } else {
      child = Container(
          decoration: BoxDecoration(
            color: color,
            border: Border.all(
              color: ColorUtil.rgba(79, 79, 102, 1), //边框颜色
              width: 1, //边框宽度
            ),
            // borderRadius: BorderRadius.only(
            //   topLeft: Radius.circular(0),
            //   topRight: Radius.circular(outerRadius),
            //   bottomLeft: Radius.circular(0),
            //   bottomRight: Radius.circular(outerRadius),
            // ),
            borderRadius: BorderRadius.circular(outerRadius),
          ),
          child: ClipRRect(
              // borderRadius: BorderRadius.only(
              //   topLeft: Radius.circular(0),
              //   topRight: Radius.circular(innerRadius),
              //   bottomLeft: Radius.circular(0),
              //   bottomRight: Radius.circular(innerRadius),
              // ),
              borderRadius: BorderRadius.circular(innerRadius),
              child: Stack(
                  alignment: AlignmentDirectional.center,
                  fit: StackFit.expand,
                  children: <Widget>[
                    _image,
                    Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment(0.3, 0),
                            colors: [Colors.black, Colors.transparent]),
                      ),
                    ),
                  ])));
    }
    return AspectRatio(
      aspectRatio: 0.75,
      child: child,
    );
  }
}
